package com.mobiftpcms.webapp.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mobiftpcms.Constants;
import com.mobiftpcms.model.Role;
import com.mobiftpcms.model.Station;
import com.mobiftpcms.model.User;
import com.mobiftpcms.service.RoleManager;
import com.mobiftpcms.service.StationManager;
import com.mobiftpcms.service.UserExistsException;
import com.mobiftpcms.service.UserManager;
import com.mobiftpcms.webapp.util.LogUtil;
import com.mobiftpcms.webapp.util.RequestUtil;

/**
 * Controller to signup new users.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Controller
@RequestMapping("/signup*")
public class SignupController extends BaseFormController {
    private RoleManager roleManager;
    
    private StationManager stationManager;

    @Autowired
    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }
    
    @Autowired
    public void setStationManager(StationManager stationManager) {
    	this.stationManager = stationManager;
    }
    
    public SignupController() {
        setCancelView("redirect:login");
        setSuccessView("redirect:mainMenu");
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    public User showForm() {
        return new User();  
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(User user, BindingResult errors, HttpServletRequest request, HttpServletResponse response)
            throws Exception {   	
    	    	
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }
        Locale locale = request.getLocale();
        
        user.setEnabled(true);

        // Set the role based the current user role
        user.addRole(RequestUtil.getRoleByCurrentUserRole(request,roleManager));
        
        user.setStation(stationManager.getStationByName(user.getStation().getName()));
        
        LogUtil.log(getUserManager(), "User Creation", "Username : "+user.getUsername(), request.getRemoteUser());

        try {
            this.getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null; 
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[]{user.getUsername(), user.getEmail()}, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            return "signup";
        }

        saveMessage(request, getText("user.registered", user.getUsername(), locale));
        request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

        // log user in automatically
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
        auth.setDetails(user);
        SecurityContextHolder.getContext().setAuthentication(auth);

        // Send user an e-mail
        if (log.isDebugEnabled()) {
            log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
        }

        // Send an account information e-mail
        message.setSubject(getText("signup.email.subject", locale));

        try {
            sendUserMessage(user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
        } catch (MailException me) {
            saveError(request, me.getMostSpecificCause().getMessage());
        }
        
        return getSuccessView();
    }
    
    @ModelAttribute("stationList")
	public Map<String, String> populateStationList(HttpServletRequest request,HttpServletResponse response) {
 
		//Data referencing for Stations Combo Box
    	Map<String, String> stations = new HashMap<String, String>();
		if(RequestUtil.isStationLevelUser(request)) {
			List<Station> allStations = stationManager.getStations();
			for(Station s:allStations) {
				stations.put(s.getName(), s.getName());
			}
		}
		return stations;
	}
    
    
    
   
}
